import { Button, Form, Input } from 'antd-mobile'

import styles from './index.module.scss'
import { useLogin } from './service'
const Login = () => {
  const { form, onFinish, mobileRef, time, sendCode } = useLogin()
  return (
    <div className={styles.root}>
      <div className="login-form">
        <h2 className="title">账号登录</h2>

        <Form form={form} onFinish={onFinish}>
          <Form.Item
            name="mobile"
            rules={[
              { required: true, message: '请输入手机号' },
              {
                pattern: /^1[3-9]\d{9}$/,
                message: '手机号格式错误',
              },
            ]}
            className="login-item">
            <Input placeholder="请输入手机号" ref={mobileRef} />
          </Form.Item>

          <Form.Item
            className="login-item"
            name="code"
            rules={[
              { required: true, message: '请输入验证码' },
              {
                pattern: /^\d{6}$/,
                message: '验证码格式错误',
              },
            ]}
            extra={
              <span
                className="code-extra"
                onClick={time ? undefined : sendCode}>
                {time ? `${time}秒后重新获取` : '发送验证码'}
              </span>
            }>
            <Input placeholder="请输入验证码" autoComplete="off" />
          </Form.Item>

          {/* noStyle 表示不提供 Form.Item 自带的样式 */}
          <Form.Item noStyle shouldUpdate>
            {/* <Button
              block
              type="submit"
              color="primary"
              className="login-submit">
              登 录
            </Button> */}
            {() => {
              // isFieldsTouched(true) 检查是否所有字段都被操作过
              const untouched = !form.isFieldsTouched(true)
              // getFieldsError() 获取所有字段名对应的错误信息
              const hasError =
                form.getFieldsError().filter(({ errors }) => errors.length)
                  .length !== 0
              const disabled = untouched || hasError
              return (
                <Button
                  block
                  type="submit"
                  color="primary"
                  className="login-submit"
                  disabled={disabled}>
                  提交
                </Button>
              )
            }}
          </Form.Item>
        </Form>
      </div>
    </div>
  )
}

export default Login
